<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '360px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      if (this.chartData && this.chartData.length > 0) {
        this.setOptions(this.chartData)
      }
    },
    setOptions(data) {
      // const data1 = [{ year: 2023, data: [0, 0, 0, 300, 0, 10102.001, 0, 0, 0, 0, 0, 0] }, { year: 2025, data: [100, 1300, 540, 300, 110, 1101, 510, 430, 1230, 1240, 1110, 2220] }]
      const years = data.map(item => item.year + '年')
      const yearsShow = {}
      years.forEach((element, index) => {
        if (index < years.length - 3) {
          yearsShow[element] = false
        }
      })
      const series = data.map(item => {
        return {
          name: item.year + '年',
          smooth: true,
          type: 'line',
          data: item.data,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        }
      })
      this.chart.setOption({
        xAxis: {
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          boundaryGap: false,
          axisTick: {
            show: false
          }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis'
        },
        yAxis: {
          axisTick: {
            show: true
          },
          minInterval: 1
        },
        legend: {
          data: years,
          selected: yearsShow
        },
        series: series
      })
    }
  }
}
</script>
